package com.gydz.gydzbaseframeworkboot.SystemControl.service.impl;

import cn.hutool.core.convert.Convert;
import com.gydz.gydzbaseframeworkboot.SystemControl.dao.UserMapper;
import com.gydz.gydzbaseframeworkboot.SystemControl.domain.User;
import com.gydz.gydzbaseframeworkboot.SystemControl.service.UserService;
import com.gydz.gydzbaseframeworkboot.Common.utils.PasswordEncoder;
import com.gydz.gydzbaseframeworkboot.Common.utils.queryParam.QueryParam;
import com.gydz.gydzbaseframeworkboot.Common.utils.result.ResultUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("UserService")
@Transactional(rollbackFor =Exception.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 查询用户
     *
     * @param id 用户主键
     * @return 用户
     */
    @Override
    public User selectUserById(Long id)
    {
        return userMapper.selectUserById(id);
    }



    /**
     * 查询用户列表
     *
     * @param queryParam 用户
     * @return 用户
     */
    @Override
    public List<User> selectUserList(QueryParam queryParam) {
        return userMapper.selectUserList(queryParam);
    }

    /**
     * 新增用户
     *
     * @param user 用户
     * @return 结果
     */
    @Override
    public int insertUser(User user)
    {
        PasswordEncoder passwordEncoder = new PasswordEncoder();
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        return userMapper.insertUser(user);
    }

    @Override
    public ResultUtils batchInsertUser(List<List<Object>> list) {
        int errorRow = 1;
        int successSize = 0;
        int failSize = 0;
        StringBuilder failureMsg = new StringBuilder();
        PasswordEncoder passwordEncoder = new PasswordEncoder();

        for (int i = 0; i < list.size(); i++) {
            try {
                List<Object> row = list.get(i);

                // 判断账号是否存在
                if (userMapper.getByUserName(row.get(2).toString()) == null) {
                    int size = row.size();
                    User user = new User();
                    if (size >= 2) user.setUserName(row.get(1).toString());
                    if (size >= 3) user.setAccount(row.get(2).toString());
                    user.setPassword(passwordEncoder.encode("123456"));
                    user.setAccountAttributes("普通用户");
                    if (size >= 4) user.setDeptName(row.get(3).toString());
                    if (size >= 5) user.setSectionName(row.get(4).toString());
                    if (size >= 6) user.setWorkshop(row.get(5).toString());
                    if (size >= 7) user.setWorkArea(row.get(6).toString());
                    errorRow++;
                    userMapper.insertUser(user);
                    successSize++;
                } else {
                    failSize++;
                    failureMsg.append("第" + (i + 2) + "行：已存在登录账号为【" + row.get(2).toString() + "】的用户 <br/>");
                }
            } catch (Exception e) {
                failSize++;
                e.printStackTrace();
                String msg = e.getMessage();
                msg = msg.replaceAll("'", "");
                failureMsg.append("第" + errorRow + "行：出现报错<br/>");
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();  //回滚
            }
        }
        Map<String, Object> map = new HashMap<>();
        if (failSize == 0) {
            map.put("message", "您已成功导入" + list.size() + "条数据");
            return ResultUtils.succ(map);
        } else {
            map.put("message", failureMsg.toString());
            map.put("successSize", successSize);
            map.put("failSize", failSize);
            return ResultUtils.fail(400, "数据异常", map);
        }
    }

    /**
     * 修改用户
     *
     * @param user 用户
     * @return 结果
     */
    @Override
    public int updateUser(User user)
    {
        if(user.getId() != null){
            PasswordEncoder passwordEncoder = new PasswordEncoder();
            user.setPassword(StringUtils.isNotBlank(user.getPassword()) ? passwordEncoder.encode(user.getPassword()) : user.getPassword());

            return userMapper.updateUser(user);
        }
        return -1;
    }

    /**
     * 批量删除用户
     *
     * @param ids 需要删除的用户主键
     * @return 结果
     */
    @Override
    public int deleteUserByIds(String ids)
    {
        return userMapper.deleteUserByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除用户信息
     *
     * @param id 用户主键
     * @return 结果
     */
    @Override
    public int deleteUserById(Long id)
    {
        return id != null ? userMapper.deleteUserById(id) : -1;
    }

    @Override
    public boolean getByUserName(String account) {
        return userMapper.getByUserName(account) != null;
    }

    @Override
    public User getByUserNameInfo(String account) {
        return userMapper.getByUserName(account);
    }

    @Override
    public boolean updateUserPwd(Long id, String password) {
        if(id != null){
            PasswordEncoder passwordEncoder = new PasswordEncoder();
            User user = new User();
            user.setId(id);
            user.setPassword(passwordEncoder.encode(password));
            userMapper.updateUserPwd(user);
            return true;
        }
        return false ;
    }

    @Override
    public boolean resetUserPwd(Long id) {
        if(id != null){
            PasswordEncoder passwordEncoder = new PasswordEncoder();
            User user = new User();
            user.setId(id);
            user.setPassword(passwordEncoder.encode("123456"));
            userMapper.updateUserPwd(user);
            return true;
        }
        return false ;
    }

}
